import {
  dsx
} from "../../../../tools/datax"
import {
  users
} from "../../../../tools/users"
import {
  pages
} from '../../../../tools/pages'
import {
  checkTool
} from "../../../../tools/check"
import {
  ui
} from "../../../../tools/ui";
import {
  coupon
} from "../../../../tools/coupon";


Page({
  data: {
    item: {}
  },
  onLoad(options) {
    this.loadCoupon(options.id)
  },
  loadCoupon(id) {
    const _ = dsx.cmd
    return dsx.coll('coupons')
      .where({
        _id: _.eq(id)
      })
      .get()
      .then(res => {
        // console.log(res.data[0])
        this.setData({
          item: res.data[0],
          id
        })
      })
  },
  async obtainTap() {
    let {
      id,
      item,
      user
    } = this.data
    if (this.loading) return
    this.loading = true

    const that = this
    ui.loading()
    // 判断领用条件
    const curUser = user || await users.getUser()
    const res = coupon.canObtain(item, curUser)
    if (!res.success) return ui.toast(false, res.errMsg, () => that.loading = false)

    // 重新加载剩余量
    await this.loadCoupon(id)
    item = this.data.item
    if (item.left * 1 <= 0) return ui.toast(false, "已被抢光", () => that.loading = false)

    // 领用并更新
    const obtainNum = Math.min(item.limit * 1, item.left * 1)
    coupon.updateCoupon(item, obtainNum)
    coupon.updateUserOpenGId(item, curUser)
    ui.loading(false)
    ui.toast(true, `已领取${obtainNum}张群优惠券，快去使用吧！`)

    // 刷新页面
    item.left = item.left * 1 - obtainNum
    this.setData({
      item
    })
    this.loading = false
  },
})